package com.ohc.笔试;

import java.util.ArrayList;

public class 简化路径 {
    public static String solution(String str) {
        StringBuilder builder = new StringBuilder();
        if ("".equals(str) || null == str)
            return null;
        ArrayList<String> list1 = new ArrayList<>();
        ArrayList<String> list2 = new ArrayList<>();
        str = str.replace("//", "/");
        String[] split = str.split("/");
        for (String s : split) {
            if (!"".equals(s) && !".".equals(s)) { // 取出路径
                list1.add(s); // ..
            }
        }
        if (list1.size() == 0) { // 说明为空，直接返回根路径
            return "/";
        }
        for (int i = 0; i < list1.size(); i++) {
            if (!list1.get(i).equals("..")) { // 不为..的才添加
                list2.add(list1.get(i));
            } else {
                if (list2.size() != 0) {
                    list2.remove(list2.size() - 1); // 如果是..的就删除前边的元素

                }
            }

        }

//        "/../" 示例2
        if (list2.size() == 0) {
            return "/";
        }


        String res = "";
        for (String s : list2) {
            res = res + "/" + s;
        }
        return res;
    }

    public static void main(String[] args) {
//        实例1 防止末尾出现/
        String s1 = "/home/";
//        实例2  没对..处理
        String s2 = "/../";
//        实例3  同1
        String s3 = "/home/foo/";
// 实例4   考察../的删除元素
        String s4 = "/a/./b/../../c/";
// 实例5     同4
        String s5 = "/a/../../b/../c//.//";
// 实例6  对// 的处理
        String s6 = "/a//b////c/d//././/..";
        String solution = solution(s6);
        System.out.println("s6 = " + s6);
        System.out.println("solution = " + solution);
    }
}
